<?php
// +----------------------------------------------------------------------
// | 通用PHP框架 [ ThinkPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 郑州智众 [Paulxun@qq.com]
// +----------------------------------------------------------------------
// | 官方网站: https://www.zzmind.com
// +----------------------------------------------------------------------

namespace app\mall\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\mall\model\Goods;
use app\mall\model\Category;
use app\admin\model\Module as ModuleModel;
use app\admin\model\Config as ConfigModel;
use app\mall\model\Order as OrderModel;
use think\facade\Db;

/**
 * 商户数据控制器
 * @package app\mall\admin
 */
class Index extends Admin
{
    /**
     * 首页
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     */
    public function index()
    {
		$user = session('user_auth');
		$this->assign('user', $user);
		$goods_list = Goods::where('status', 1)->column('title', 'id');
		$this->assign('goods_list', $goods_list);
		if (request()->isAjax()) {
			$data = request()->post();
			$count = false;
			$time = time();
			// 统计最近10日的列表
			$count_list = [];
			if (!empty($data['time_from']) && !empty($data['time_to'])) {
				$from = strtotime($data['time_from']);
				$to = strtotime($data['time_to']);
				$days = ($to - $from) / (3600 *24);
				$time = $to + 3600 * 24 - 1;
				if ($days > 31) $this->error('时间区间不能超过31天');
				for ($i=0; $i<=$days; $i++) {
					$time = $time - 3600*24;
					$count_map = [
						['pay_time', 'between', [$time + 1, $time + 3600*24]],
					];
					$oids = OrderModel::where($count_map)->column('id');
					$map = [
						['oid', 'in', $oids],
					];
					if (!empty($data['goods']) && $data['goods'] > 0) $map[] = ['gid', '=', $data['goods']];
					$counts = Db::name('mall_order_detail')->where($map)->field('sum(balance) as balance, sum(second) as second, sum(realpay) as realpay, sum(number) as number, sum(pay_price) as pay_price, sum(number) as total')->find();
					if ($counts){
						$counts['day'] = format_date($time + 1);
						$count_list[] = $counts;
					}
				}
			} else {
				for ($i=0; $i<10; $i++) {
					$time = $time - 3600*24;
					$count_map = [
						['pay_time', 'between', [$time + 1, $time + 3600*24]],
					];
					$oids = OrderModel::where($count_map)->column('id');
					$map = [
						['oid', 'in', $oids],
					];
					if (!empty($data['goods']) && $data['goods'] > 0) $map[] = ['gid', '=', $data['goods']];
					$counts = Db::name('mall_order_detail')->where($map)->field('sum(balance) as balance, sum(second) as second, sum(realpay) as realpay, sum(number) as number, sum(pay_price) as pay_price, sum(number) as total')->find();
					if ($counts){
						$counts['day'] = format_date($time + 1);
						$count_list[] = $counts;
					} 
				}
			}
			// 以相反的元素顺序返回数组
			$count_list = array_reverse($count_list);
			foreach ($count_list as $key => $value){
				$count_list[$key]['balance'] = $value['balance'] / 100;
				$count_list[$key]['second'] = $value['second'] / 100;
				$count_list[$key]['realpay'] = $value['realpay'] / 100;
				$count_list[$key]['pay_price'] = $value['pay_price'] / 100;
			}
			$return = [];
			$sum = array_column($count_list, 'pay_price');
			$sum_total = array_sum($sum);
			$return['title']['text'] = '全部商品统计：￥'.$sum_total;
			if (isset($data['goods']) && $data['goods'] > 0) {
				if (isset($goods_list[$data['goods']])) $return['title']['text'] = $goods_list[$data['goods']].'统计：￥'.$sum_total;
			}
			$return['xAxis']['data'] = array_column($count_list, 'day');
			$return['yAxis']['show'] = true;
			$legends = ['出货量', '首单支付', '补货余额支付', '现金支付', '成交总金额'];
			// $return['total'] = array_column($count_list, 'total');
			// $return['wx_total'] = array_column($count_list, 'wx_total');
			// $return['ali_total'] = array_column($count_list, 'ali_total');
			$return['series'] = [];
			foreach ($legends as $key => $legend){
				$label = false;
				switch ($key) {
					case 0 :
					$type = 'line';
					$stack = false;
					$label = true;
					$data = array_column($count_list, 'total');
					break;
					case 1 :
					$type = 'bar';
					$stack = '成交金额';
					$data = array_column($count_list, 'balance');
					break;
					case 2 :
					$type = 'bar';
					$stack = '成交金额';
					$data = array_column($count_list, 'second');
					break;
					case 3 :
					$type = 'bar';
					$stack = '成交金额';
					$data = array_column($count_list, 'realpay');
					break;
					case 4 :
					$type = 'line';
					$stack = false;
					$label = true;
					$data = array_column($count_list, 'pay_price');
					break;
					default :
					$type = 'line';
					$stack = false;
					$data = [];
				}
				$series = [
					'name' => $legend,
					'type' => $type,
					'data' => $data,
				];
				if ($stack != false) $series['stack'] = $stack;
				if (isset($label) && $label === true) $series['label'] = ['show' => true, 'position' => 'top'];
				$return['series'][] = $series;
			}
			$this->success('请求成功', '', $return);
		}
        $this->assign('goods', Goods::where('status', 1)->count('id')); // 商品
        $this->assign('orders',OrderModel::where('status', '>', 0)->count('id')); // 订单数
		$this->assign('users', Db::name('user_member')->where('status', 1)->count('id')); //用户
		$this->assign('vips', Db::name('user_vip')->where('status', 1)->count('member_id')); //会员
		
        $this->assign('page_title', '商城数据');
        return $this->fetch(); // 渲染模板
    }
	/**
	 * 系统设置
	 * @author PaulXun <paulxun@qq.com>
	 * @return mixed
	 * @throws \think\Exception
	 * @throws \think\exception\PDOException
	 */
	public function setting()
	{
	    // 保存数据
	    if ($this->request->isPost()) {
	        $data = $this->request->post();
			//var_dump($data);
	        if (isset(config('app.config_group')['mall'])) {
	            // 查询该分组下所有的配置项名和类型
	            $items = ConfigModel::where('group', 'mall')->where('status', 1)->column('type','name');
				//var_dump($items);
	            foreach ($items as $name => $type) {
					//var_dump($name);
					//var_dump($type);
					//var_dump($data[$name]);
	                if (!isset($data[$name])) {
	                    switch ($type) {
	                        // 开关
	                        case 'switch':
	                            $data[$name] = 0;
	                            break;
	                        case 'checkbox':
	                            $data[$name] = '';
	                            break;
	                    }
	                } else {
	                    // 如果值是数组则转换成字符串，适用于复选框等类型
	                    if (is_array($data[$name])) {
	                        $data[$name] = implode(',', $data[$name]);
	                    }
	                    switch ($type) {
	                        // 开关
	                        case 'switch':
	                            $data[$name] = 1;
	                            break;
	                        // 日期时间
	                        case 'date':
	                        case 'time':
	                        case 'datetime':
	                            $data[$name] = strtotime($data[$name]);
	                            break;
							default:
								$data[$name] = trim($data[$name]);
	                    }
	                }
					
	                ConfigModel::where('name', $name)->update(['value' => $data[$name]]);
	            }
	        } else {
	            // 保存模块配置
				if (isset($data['__token__'])) unset($data['__token__']);
	            if (false === ModuleModel::where('name', 'mall')->update(['config' => json_encode($data)])) {
	                $this->error('更新失败');
	            }
	            // 非开发模式，缓存数据
	            if (config('app.develop_mode') == 0) {
	                cache('module_config_'.'mall', $data);
	            }
	        }
	        cache('system_config', null);
	        // 记录行为
	        action_log('system_config_update', 'admin_config', 0, UID, "分组('mall')");
	        $this->success('更新成功');
	    } else {
	        // 配置分组信息
	        $list_group = config('app.config_group');
	
	        // 读取模型配置
	        $modules = ModuleModel::where('config', '<>', '')
	            ->where('status', 1)
	            ->column('config,title,name', 'name');
	        foreach ($modules as $name => $module) {
	            $list_group[$name] = $module['title'];
	        }
	
	        $tab_list = [];
	        foreach ($list_group as $key => $value) {
	            $tab_list[$key]['title'] = $value;
	            $tab_list[$key]['url']   = url('index', ['group' => $key]);
	        }
	
	        if (isset(config('app.config_group')['mall'])) {
	            // 查询条件
	            $map['group']  = 'mall';
	            $map['status'] = 1;
	
	            // 数据列表
	            $data_list = ConfigModel::where($map)
	                ->order('sort asc,id asc')
	                ->withoutField('group')
	                ->select();
	            $data_list = $data_list->toArray();
	
	            foreach ($data_list as &$value) {
	                // 解析options
	                if ($value['options'] != '') {
	                    $value['options'] = parse_attr($value['options']);
	                }
	                // 默认模块列表
	                if ($value['name'] == 'home_default_module') {
	                    $value['options'] = array_merge(['index' => '默认'], ModuleModel::getModule());
	                }
	                switch ($value['type']) {
	                    // 日期时间
	                    case 'date':
	                        $value['value'] = $value['value'] != '' ? date('Y-m-d', $value['value']) : '';
	                        break;
	                    case 'time':
	                        $value['value'] = $value['value'] != '' ? date('H:i:s', $value['value']) : '';
	                        break;
	                    case 'datetime':
	                        $value['value'] = $value['value'] != '' ? date('Y-m-d H:i:s', $value['value']) : '';
	                        break;
	                    case 'linkages':
	                        $value['token'] = $this->createLinkagesToken($value['table'], $value['option'], $value['key']);
	                        break;
	                    case 'colorpicker':
	                        $value['mode'] = 'rgba';
	                        break;
	                }
	            }
	
	            // 使用ZBuilder快速创建表单
	            return ZBuilder::make('form')
	                ->setPageTitle('系统设置')
	                //->setTabNav($tab_list, 'mall')
	                ->setFormItems($data_list)
	                ->fetch();
	        } else {
	            // 模块配置
	            $module_info = ModuleModel::getInfoFromFile('mall');
	            $config      = $module_info['config'];
	            $trigger     = isset($module_info['trigger']) ? $module_info['trigger'] : [];
	
	            // 数据库内的模块信息
	            $db_config = ModuleModel::where('name', 'mall')->value('config');
	            $db_config = json_decode($db_config, true);
	
	            // 使用ZBuilder快速创建表单
	            return ZBuilder::make('form')
	                ->setPageTitle('商城设置')
	                //->setTabNav($tab_list, 'mall')
	                ->addFormItems($config)
	                ->setFormdata($db_config) // 设置表格数据
	                ->setTrigger($trigger) // 设置触发
	                ->fetch();
	        }
	    }
	}
}
